package com.small.xx.ai.apidoc.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.small.xx.ai.apidoc.entity.ApiInfo;
import com.small.xx.ai.apidoc.dto.ApiInfoRequest;
import com.small.xx.ai.apidoc.dto.ApiInfoResponse;
import com.small.xx.ai.apidoc.entity.AppService;
import com.small.xx.ai.apidoc.dto.AppServiceResponse;
import com.small.xx.ai.apidoc.mapper.ApiInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * API信息服务类
 */
@Service
public class ApiInfoService extends ServiceImpl<ApiInfoMapper, ApiInfo> {
    
    @Autowired
    private AppServiceService appServiceService;
    
    @Autowired
    private ApiInfoMapper apiInfoMapper;
    
    /**
     * 创建API信息
     * 
     * @param request API信息请求
     * @return API信息响应
     */
    public ApiInfoResponse createApi(ApiInfoRequest request) {
        ApiInfo apiInfo = new ApiInfo();
        apiInfo.setName(request.getName());
        apiInfo.setDescription(request.getDescription());
        apiInfo.setMethod(request.getMethod());
        apiInfo.setPath(request.getPath());
        apiInfo.setAppServiceId(request.getAppServiceId()); // 设置应用服务ID
        apiInfo.setRequestParams(request.getRequestParams());
        apiInfo.setRequestExample(request.getRequestExample());
        apiInfo.setResponseExample(request.getResponseExample());
        apiInfo.setCreateTime(LocalDateTime.now());
        apiInfo.setUpdateTime(LocalDateTime.now());
        
        apiInfoMapper.insert(apiInfo);
        
        return convertToResponse(apiInfo);
    }
    
    /**
     * 根据ID获取API信息
     * 
     * @param id API ID
     * @return API信息响应
     */
    public ApiInfoResponse getApiById(Long id) {
        ApiInfo apiInfo = apiInfoMapper.selectById(id);
        return apiInfo != null ? convertToResponse(apiInfo) : null;
    }
    
    /**
     * 获取所有API信息
     * 
     * @return API信息响应列表
     */
    public List<ApiInfoResponse> getAllApis() {
        return apiInfoMapper.selectList(null).stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());
    }
    
    /**
     * 更新API信息
     * 
     * @param id API ID
     * @param request API信息请求
     * @return API信息响应
     */
    public ApiInfoResponse updateApi(Long id, ApiInfoRequest request) {
        ApiInfo apiInfo = apiInfoMapper.selectById(id);
        if (apiInfo == null) {
            return null;
        }
        
        apiInfo.setName(request.getName());
        apiInfo.setDescription(request.getDescription());
        apiInfo.setMethod(request.getMethod());
        apiInfo.setPath(request.getPath());
        apiInfo.setAppServiceId(request.getAppServiceId()); // 更新应用服务ID
        apiInfo.setRequestParams(request.getRequestParams());
        apiInfo.setRequestExample(request.getRequestExample());
        apiInfo.setResponseExample(request.getResponseExample());
        apiInfo.setUpdateTime(LocalDateTime.now());
        
        apiInfoMapper.updateById(apiInfo);
        
        return convertToResponse(apiInfo);
    }
    
    /**
     * 删除API信息
     * 
     * @param id API ID
     * @return 是否删除成功
     */
    public boolean deleteApi(Long id) {
        return apiInfoMapper.deleteById(id) > 0;
    }
    
    /**
     * 测试API接口
     * 
     * @param id API ID
     * @param testParams 测试参数
     * @return 测试结果
     */
    public String testApi(Long id, String testParams) {
        ApiInfo apiInfo = apiInfoMapper.selectById(id);
        if (apiInfo == null) {
            return "API not found";
        }
        
        // 获取关联的应用服务信息
        AppServiceResponse appService = null;
        if (apiInfo.getAppServiceId() != null) {
            appService = appServiceService.getAppServiceById(apiInfo.getAppServiceId());
        }
        
        // 构建完整的API URL
        StringBuilder baseUrl = new StringBuilder();
        if (appService != null) {
            baseUrl.append(appService.getBaseUrl());
        } else {
            baseUrl.append("http://localhost:8080"); // 默认地址
        }
        
        // 拼接完整URL
        String fullPath = apiInfo.getPath();
        if (!fullPath.startsWith("/")) {
            fullPath = "/" + fullPath;
        }
        String fullUrl = baseUrl.toString() + fullPath;
        
        // 实际调用API
        try {
            String response = sendHttpRequestWithHutool(fullUrl, apiInfo.getMethod(), testParams, null);
            
            // 构建结果
            StringBuilder result = new StringBuilder();
            result.append("API测试结果:\n");
            result.append("API名称: ").append(apiInfo.getName()).append("\n");
            result.append("请求方法: ").append(apiInfo.getMethod()).append("\n");
            result.append("完整URL: ").append(fullUrl).append("\n");
            result.append("测试参数: ").append(testParams).append("\n");
            result.append("响应结果: ").append(response).append("\n");
            result.append("测试时间: ").append(LocalDateTime.now()).append("\n");
            
            // 如果有关联的应用服务，显示应用服务信息
            if (appService != null) {
                result.append("\n关联应用服务信息:\n");
                result.append("- 服务名称: ").append(appService.getName()).append("\n");
                result.append("- 协议: ").append(appService.getProtocol()).append("\n");
                result.append("- IP地址: ").append(appService.getIpAddress()).append("\n");
                result.append("- 端口: ").append(appService.getPort()).append("\n");
                result.append("- 上下文路径: ").append(appService.getContextPath()).append("\n");
            }
            
            return result.toString();
        } catch (Exception e) {
            return "API调用失败: " + e.getMessage();
        }
    }
    
    /**
     * 增强API测试接口
     * 
     * @param id API ID
     * @param testRequest 测试请求参数
     * @return 测试结果
     */
    public String testAdvancedApi(Long id, Map<String, Object> testRequest) {
        ApiInfo apiInfo = apiInfoMapper.selectById(id);
        if (apiInfo == null) {
            return "API not found";
        }
        
        // 获取关联的应用服务信息
        AppServiceResponse appService = null;
        if (apiInfo.getAppServiceId() != null) {
            appService = appServiceService.getAppServiceById(apiInfo.getAppServiceId());
        }
        
        // 获取测试参数
        String url = (String) testRequest.get("url");
        String method = (String) testRequest.get("method");
        Map<String, String> headers = (Map<String, String>) testRequest.get("headers");
        String body = (String) testRequest.get("body");
        Map<String, String> formData = (Map<String, String>) testRequest.get("formData");
        Boolean isFormData = (Boolean) testRequest.get("isFormData");
        
        // 如果没有提供URL，则构建完整的API URL
        if (url == null || url.isEmpty()) {
            // 构建完整的API URL
            StringBuilder baseUrl = new StringBuilder();
            if (appService != null) {
                baseUrl.append(appService.getBaseUrl());
            } else {
                baseUrl.append("http://localhost:8080"); // 默认地址
            }
            
            // 拼接完整URL
            String fullPath = apiInfo.getPath();
            if (!fullPath.startsWith("/")) {
                fullPath = "/" + fullPath;
            }
            url = baseUrl.toString() + fullPath;
        }
        
        // 如果没有提供method，则使用API的原始方法
        if (method == null || method.isEmpty()) {
            method = apiInfo.getMethod();
        }
        
        // 实际调用API
        try {
            String response = sendHttpRequestWithHutoolAdvanced(url, method, body, formData, headers);
            
            // 构建结果
            StringBuilder result = new StringBuilder();
            result.append("API增强测试结果:\n");
            result.append("API名称: ").append(apiInfo.getName()).append("\n");
            result.append("请求方法: ").append(method).append("\n");
            result.append("完整URL: ").append(url).append("\n");
            
            // 显示Headers
            if (headers != null && !headers.isEmpty()) {
                result.append("请求头:\n");
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    result.append("  ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
                }
            }
            
            // 显示Body
            if (body != null && !body.isEmpty()) {
                result.append("请求体:\n").append(body).append("\n");
            }
            
            // 显示FormData
            if (formData != null && !formData.isEmpty()) {
                result.append("表单数据:\n");
                for (Map.Entry<String, String> entry : formData.entrySet()) {
                    result.append("  ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
                }
            }
            
            result.append("响应结果: ").append(response).append("\n");
            result.append("测试时间: ").append(LocalDateTime.now()).append("\n");
            
            // 如果有关联的应用服务，显示应用服务信息
            if (appService != null) {
                result.append("\n关联应用服务信息:\n");
                result.append("- 服务名称: ").append(appService.getName()).append("\n");
                result.append("- 协议: ").append(appService.getProtocol()).append("\n");
                result.append("- IP地址: ").append(appService.getIpAddress()).append("\n");
                result.append("- 端口: ").append(appService.getPort()).append("\n");
                result.append("- 上下文路径: ").append(appService.getContextPath()).append("\n");
            }
            
            return result.toString();
        } catch (Exception e) {
            return "API调用失败: " + e.getMessage();
        }
    }
    
    /**
     * 使用Hutool发送HTTP请求（增强版）
     * 
     * @param urlStr 请求URL
     * @param method 请求方法
     * @param body 请求体
     * @param formData 表单数据
     * @param headers 请求头
     * @return 响应结果
     */
    private String sendHttpRequestWithHutoolAdvanced(String urlStr, String method, String body, Map<String, String> formData, Map<String, String> headers) {
        // 创建HTTP请求
        HttpRequest request = HttpRequest.of(urlStr);
        
        // 设置请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.header(entry.getKey(), entry.getValue());
            }
        }
        request.method(Method.valueOf(method));
        // 设置请求方法和发送请求
        HttpResponse response = null;
        switch (method.toUpperCase()) {
            case "GET":
                response = request.execute();
                break;
            case "POST":
                if (formData != null && !formData.isEmpty()) {
                    // 处理表单数据
                    for (Map.Entry<String, String> entry : formData.entrySet()) {
                        request.form(entry.getKey(), entry.getValue());
                    }
                    response = request.execute();
                } else {
                    // 处理JSON数据
                    response = request.body(body).execute();
                }
                break;
            case "PUT":
                if (formData != null && !formData.isEmpty()) {
                    // 处理表单数据
                    for (Map.Entry<String, String> entry : formData.entrySet()) {
                        request.form(entry.getKey(), entry.getValue());
                    }
                    response = request.execute();
                } else {
                    // 处理JSON数据
                    response = request.body(body).execute();
                }
                break;
            case "DELETE":
                response = request.execute();
                break;
            case "HEAD":
                response = request.execute();
                break;
            case "OPTIONS":
                response = request.execute();
                break;
            default:
                response = request.execute();
        }
        
        // 返回响应结果
        return "HTTP " + response.getStatus() + "\n" + response.body();
    }
    
    /**
     * 使用Hutool发送HTTP请求
     * 
     * @param urlStr 请求URL
     * @param method 请求方法
     * @param body 请求体
     * @param headers 请求头
     * @return 响应结果
     */
    private String sendHttpRequestWithHutool(String urlStr, String method, String body, Map<String, String> headers) {
        // 创建HTTP请求
        HttpRequest request = HttpRequest.of(urlStr);
        
        // 设置请求头
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                request.header(entry.getKey(), entry.getValue());
            }
        }
        
        // 设置请求方法和发送请求
        HttpResponse response = null;
        switch (method.toUpperCase()) {
            case "GET":
                response = request.execute();
                break;
            case "POST":
                response = request.body(body).execute();
                break;
            case "PUT":
                response = request.body(body).execute();
                break;
            case "DELETE":
                response = request.execute();
                break;
            case "HEAD":
                response = request.execute();
                break;
            case "OPTIONS":
                response = request.execute();
                break;
            default:
                response = request.execute();
        }
        
        // 返回响应结果
        return "HTTP " + response.getStatus() + "\n" + response.body();
    }
    
    /**
     * 将ApiInfo转换为ApiInfoResponse
     * 
     * @param apiInfo API信息实体
     * @return API信息响应
     */
    private ApiInfoResponse convertToResponse(ApiInfo apiInfo) {
        ApiInfoResponse response = new ApiInfoResponse();
        response.setId(apiInfo.getId());
        response.setName(apiInfo.getName());
        response.setDescription(apiInfo.getDescription());
        response.setMethod(apiInfo.getMethod());
        response.setPath(apiInfo.getPath());
        response.setAppServiceId(apiInfo.getAppServiceId()); // 设置应用服务ID
        response.setRequestParams(apiInfo.getRequestParams());
        response.setRequestExample(apiInfo.getRequestExample());
        response.setResponseExample(apiInfo.getResponseExample());
        response.setCreateTime(apiInfo.getCreateTime());
        response.setUpdateTime(apiInfo.getUpdateTime());
        return response;
    }
}